import { ThingSizeModel } from "./base/model";

const racketWidth = 1350;
const racketHeight = 20;

// 球拍
export class Racket {
    private racketHandler: PIXI.Graphics;
    constructor(private app: PIXI.Application) {
        this.racketHandler = this.initRacket();

        this.attachEvent();
    }

    /**
     * 初始化球拍
     */
    private initRacket(): PIXI.Graphics {
        let lineColor = 0xFEEB77;
        let fillColor = 0x650A5A;
        const graphics = new PIXI.Graphics();

        // Rectangle 2
        graphics.lineStyle(2, lineColor, 1);
        graphics.beginFill(fillColor);
        // graphics.drawRect(this.app.view.width / 2 - racketWidth / 2, this.app.view.height - 20 - 2, racketWidth, 20);
        graphics.drawRect(0, 0, racketWidth, racketHeight);
        graphics.endFill();

        this.app.stage.addChild(graphics);
        graphics.position.y = this.app.view.height - racketHeight - 2;
        graphics.position.x = this.app.view.width / 2 - racketWidth / 2;
        return graphics;
    }

    private attachEvent(){
        window.addEventListener('keydown', e => {
            switch (e.key) {
                case "ArrowRight":
                    this.moveRight();
                    break;
                case "ArrowLeft":
                    this.moveLeft();
                    break;
            }
        });
    }

    private moveLeft() {
        this.racketHandler.position.x -= 20;
        this.fix();
    }

    private moveRight() {
        this.racketHandler.position.x += 20;
        this.fix();
    }

    private fix(){
        if (this.racketHandler.position.x < 0) {
            this.racketHandler.position.x = 0;
            return;
        }

        if (this.racketHandler.position.x > this.app.view.width - racketWidth) {
            this.racketHandler.position.x = this.app.view.width - racketWidth;
            return;
        }
    }

    public hasCollision(size: ThingSizeModel): boolean {
        let curOffsetX = this.racketHandler.position.x;
        let curOffsetY = this.racketHandler.position.y;

        if (size.x2 < curOffsetX || size.x1 > curOffsetX + racketWidth) {
            return false;
        }

        if (size.y2 > curOffsetY && curOffsetY + racketHeight > size.y2) {
            return true;
        }

        return false;
    }
}
